package com.yanghui.listener;

import com.yanghui.pojo.Visit;
import com.yanghui.service.VisitService;

import com.yanghui.utils.AddressUtil;
import com.yanghui.utils.UserAgentUtil;
import com.yanghui.utils.UserIpUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 监听访客
 */
public class VisitTimesListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        HttpSession session = request.getSession();
        ServletContext servletContext = session.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        VisitService visitService = applicationContext.getBean(VisitService.class);
        /** 如果是新会话 */
        if (session.isNew()) {
            Visit visit = new Visit();
            visit.setIp(UserIpUtil.getIp(request));
            visit.setTime(new Date());
            /** 获取请求头 */
            String userAgent = request.getHeader("user-agent");
            visit.setUserAgent(userAgent);

            synchronized (this) {
                if (visitService.findVisitTimes(visit) == false) {
                    visit.setPlatformType(UserAgentUtil.getUserAgent(userAgent).getPlatformType());
                    visit.setBrowserType(UserAgentUtil.getUserAgent(userAgent).getBrowserType());
                    visit.setUrl(request.getRequestURL().toString());
                    try {
                        visit.setCity(new AddressUtil().getAddresses("ip=" + visit.getIp(),
                                "UTF-8"));
                        /** 向数据库中插入访客记录 */
                        visitService.addVisit(visit);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}
